//
//  WEXUserAccountViewModel.swift
//  microBlog
//
//  Created by apple on 16/4/19.
//  Copyright © 2016年 Hill. All rights reserved.
//

import UIKit
import SVProgressHUD

class WEXUserAccountViewModel: NSObject {

//    实现viewModel的单例
    static let sharedViewModel: WEXUserAccountViewModel = WEXUserAccountViewModel()
    
    override init() {
        super.init()
        self.account = accountInSandBox()
    }
    
    // MARK: - 记录账户
    var account: WEXUserAccountModel?
    
    
    // MARK: - 用户授权信息
    var accessToken: String? {
        
        return self.account?.access_token
    }
    
    // MARK: - 记录是否登录
    var isLogin: Bool  {
        
//        判断是否取到用户授权信息
        if accessToken == nil {
            
            return false
        }
        
//        判断授权是否过期
        guard let expires = self.account?.expiresTime else {
            
            return false
        }
        
        if NSDate().compare(expires) == .OrderedAscending {
            
            return true
        }
        
        return false
    }
    
    
    // MARK: - 加载accessoToken
    //抽出完代码以后，通过闭包的方式通知控制器
    func loadAccessToken(code: String, finished:(isSuccess: Bool)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //        设置参数
        let params = [
            "client_id": WB_APP_KEY,
            "client_secret": WB_APP_SECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_REDIRECT_URI
        ]
        
        WEXNetworkTools.sharedTools.request(.Post, urlString: urlString, parameters: params) { (responseObject, error) -> () in
            
            if error != nil {
                
                print(error)
                
                finished(isSuccess: false)
                
                return
            }
            
//            print("请求成功\(responseObject)")
            
            //            判断格式
            guard let dict = responseObject as? [String: AnyObject] else {
                
                print("返回格式错误")
                
                finished(isSuccess: false)
                
                return
            }
            
            //            字典转模型
            let account = WEXUserAccountModel(dict: dict)
//            print(account)
            self.account = account
            
            self.loadAccout(account, finished: finished)
            
        }
        
    }
    
    
    // MARK: - 加载账户信息
    private func loadAccout(account: WEXUserAccountModel, finished: (isSuccess: Bool)->()){
        
        //        通过文档获得请求地址
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        //        设置参数
        let params = [
            "access_token": account.access_token ?? "",
            "uid": account.uid ?? ""
        ]
        
        WEXNetworkTools.sharedTools.request(.Get, urlString: urlString, parameters: params) { (responseObject, error) -> () in
            
            
            if error != nil {
                
                SVProgressHUD.showErrorWithStatus("网络错误")
                
                finished(isSuccess: false)
                
                return
            }
            
            
//            print(responseObject)
            guard let dict = responseObject as? [String: AnyObject] else {
                
                print("格式错误")
                finished(isSuccess: false)
                
                return
            }
            
            //            赋值，因为前面的值为可选项，所以，此处as后面跟？
            account.name = dict["name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            
            self.account = account
            self.saveToSandBox(account)
            
            finished(isSuccess: true)
        }
        
        
    }
    
    // MARK: - 归档
    private func saveToSandBox(account: WEXUserAccountModel) {
        
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
        
        NSKeyedArchiver.archiveRootObject(account, toFile: path)
        
        
    }
    
    
    // MARK: - 解档
    private func accountInSandBox() -> WEXUserAccountModel? {
        
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
        
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? WEXUserAccountModel
        
//        print(result)
        
        return result
        
        
    }

    
    
}
